package com.xie.smfs.common.events;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.attribute.EntityAttribute;
import net.minecraft.entity.attribute.EntityAttributeInstance;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.network.ServerPlayerEntity;
import com.xie.smfs.effect.SpiritAttributes;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xie.smfs.item.SilentGhostEyeItem;
import com.xie.smfs.client.data.ClientDataManager;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class PlayerEvents {
    private static final Logger LOGGER = LoggerFactory.getLogger("smfs/PlayerEvents");

    // 使用正确的键来存储数据（与Mixin中保持一致）
    public static final String SMFS_DATA_KEY = "smfs_spirit_data";
    private static final String GHOST_SLOTS_KEY = "GhostSlots";

    // 内存缓存，提高性能
    private static final Map<UUID, NbtCompound> PLAYER_DATA_CACHE = new HashMap<>();

    public static void register() {
        // 玩家加入时初始化数据
        ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
            ServerPlayerEntity player = handler.getPlayer();
            // 从玩家NBT加载数据到缓存
            loadPlayerDataToCache(player);
            // 初始化属性
            initPlayerAttributes(player);
        });

        // 延迟清理缓存，确保数据保存完成
        ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> {
            ServerPlayerEntity player = handler.getPlayer();
            server.submit(() -> PLAYER_DATA_CACHE.remove(player.getUuid()));
        });

        // 玩家重生时复制数据
        ServerPlayerEvents.COPY_FROM.register((oldPlayer, newPlayer, alive) -> {
            copySpiritAttributes(oldPlayer, newPlayer);
            initPlayerAttributes(newPlayer);
        });
    }

    // 创建默认的灵异数据
    private static NbtCompound createDefaultSpiritData() {
        NbtCompound data = new NbtCompound();

        // 初始化六个灵异槽位
        NbtCompound ghostSlots = new NbtCompound();
        for (int i = 0; i < 6; i++) {
            NbtCompound slotData = new NbtCompound();
            slotData.putBoolean("occupied", false);
            slotData.put("item", ItemStack.EMPTY.writeNbt(new NbtCompound()));
            slotData.putInt("level", 1);
            slotData.putInt("revivalDegree", 0);
            slotData.putInt("requiredRevivalDegree", 100);
            ghostSlots.put("Slot" + i, slotData);
        }
        data.put(GHOST_SLOTS_KEY, ghostSlots);

        // 添加默认灵异属性值到NBT
        data.putDouble("spiritResistance", 0.0);
        data.putDouble("spiritDamage", 0.0);
        data.putDouble("currentSpirit", 0.0);
        data.putDouble("maxSpirit", 0.0);
        data.putDouble("revivalFactor", 0.0);
        data.putDouble("sanity", 100.0);
        data.putInt("ghostEyeRecoveryPoints", 0);

        return data;
    }
    // 从玩家NBT加载数据到缓存
    private static void loadPlayerDataToCache(PlayerEntity player) {
        NbtCompound playerNbt = player.writeNbt(new NbtCompound());
        // 创建默认数据作为基础
        NbtCompound spiritData = createDefaultSpiritData();
        
        if (playerNbt.contains(SMFS_DATA_KEY)) {
            NbtCompound existingData = playerNbt.getCompound(SMFS_DATA_KEY);
            // 合并现有数据到默认数据中（保留现有值，补充缺失值）
            for (String key : existingData.getKeys()) {
                if (spiritData.contains(key)) {
                    spiritData.put(key, existingData.get(key).copy());
                }
            }
            PLAYER_DATA_CACHE.put(player.getUuid(), spiritData);
            LOGGER.info("已合并玩家 {} 的灵异数据到缓存", player.getName().getString());
        } else {
            // 直接使用默认数据
            PLAYER_DATA_CACHE.put(player.getUuid(), spiritData);
            LOGGER.info("为玩家 {} 初始化新的灵异数据", player.getName().getString());
        }
    }
    // 从缓存获取玩家数据
    private static NbtCompound getCachedData(PlayerEntity player) {
        return PLAYER_DATA_CACHE.computeIfAbsent(player.getUuid(), uuid -> createDefaultSpiritData());
    }

    // 保存数据回玩家NBT（由Mixin调用）
    public static void saveDataToPlayer(PlayerEntity player, NbtCompound spiritData) {
        PLAYER_DATA_CACHE.put(player.getUuid(), spiritData);
        // 实际的NBT保存由Mixin处理
    }
    //复制玩家数据
    private static void copySpiritAttributes(PlayerEntity oldPlayer, PlayerEntity newPlayer) {
        NbtCompound oldData = getCachedData(oldPlayer);
        PLAYER_DATA_CACHE.put(newPlayer.getUuid(), oldData.copy());
        LOGGER.info("已复制玩家 {} 的灵异数据到新玩家", oldPlayer.getName().getString());
    }

    // 初始化属性容器 - 重命名以避免冲突
    public static void initPlayerAttributes(PlayerEntity player) {
        setDefaultAttribute(player, SpiritAttributes.CURRENT_SPIRIT, 0.0);
        setDefaultAttribute(player, SpiritAttributes.MAX_SPIRIT, 0.0);
        setDefaultAttribute(player, SpiritAttributes.SPIRIT_RESISTANCE, 0.0);
        setDefaultAttribute(player, SpiritAttributes.SPIRIT_DAMAGE, 0.0);
        setDefaultAttribute(player, SpiritAttributes.REVIVAL_FACTOR, 0.0);
        setDefaultAttribute(player, SpiritAttributes.SANITY, 100.0);

        LOGGER.info("已初始化玩家 {} 的灵异属性", player.getName().getString());
    }

    // 设置默认属性值
    private static void setDefaultAttribute(PlayerEntity player, EntityAttribute attribute, double defaultValue) {
        EntityAttributeInstance instance = player.getAttributeInstance(attribute);
        if (instance != null && instance.getBaseValue() == 0.0) {
            instance.setBaseValue(defaultValue);
        }
    }

    // 获取灵异属性值
    public static float getSpiritAttribute(PlayerEntity player, EntityAttribute attribute) {
        EntityAttributeInstance instance = player.getAttributeInstance(attribute);
        return instance != null ? (float) instance.getValue() : 0.0f;
    }

    // 设置灵异属性值
    public static void setSpiritAttribute(PlayerEntity player, EntityAttribute attribute, float value) {
        EntityAttributeInstance instance = player.getAttributeInstance(attribute);
        if (instance != null) {
            instance.setBaseValue(value);
        }
    }

    // 增加灵异属性值
    public static void addSpiritAttribute(PlayerEntity player, EntityAttribute attribute, float amount) {
        float current = getSpiritAttribute(player, attribute);
        setSpiritAttribute(player, attribute, current + amount);
    }

    // 减少灵异属性值
    public static void subtractSpiritAttribute(PlayerEntity player, EntityAttribute attribute, float amount) {
        float current = getSpiritAttribute(player, attribute);
        setSpiritAttribute(player, attribute, Math.max(0, current - amount));
    }

    // 获取玩家的当前灵异值
    public static float getCurrentSpirit(PlayerEntity player) {
        return getSpiritAttribute(player, SpiritAttributes.CURRENT_SPIRIT);
    }

    // 获取玩家的最大灵异值
    public static float getMaxSpirit(PlayerEntity player) {
        return getSpiritAttribute(player, SpiritAttributes.MAX_SPIRIT);
    }

    // 设置玩家的当前灵异值
    public static void setCurrentSpirit(PlayerEntity player, float value) {
        float maxSpirit = getMaxSpirit(player);
        setSpiritAttribute(player, SpiritAttributes.CURRENT_SPIRIT, Math.min(value, maxSpirit));
    }

    // 设置玩家的最大灵异值
    public static void setMaxSpirit(PlayerEntity player, float value) {
        setSpiritAttribute(player, SpiritAttributes.MAX_SPIRIT, value);
        // 确保当前灵异值不超过新的最大值
        float current = getCurrentSpirit(player);
        if (current > value) {
            setCurrentSpirit(player, value);
        }
    }

    // 获取灵异属性（从缓存）
    public static NbtCompound getSpiritAttributes(PlayerEntity player) {
        return getCachedData(player).copy();
    }

    // 设置灵异属性（更新缓存）
    public static void setSpiritAttributes(PlayerEntity player, NbtCompound data) {
        PLAYER_DATA_CACHE.put(player.getUuid(), data.copy());
        // 同步到客户端
        if (player instanceof ServerPlayerEntity serverPlayer) {
            sendSpiritDataToClient(serverPlayer);
        }
        LOGGER.debug("玩家 {} 的灵异属性已更新到缓存并同步到客户端", player.getName().getString());
    }
    // 发送玩家的当前灵异数据到客户端
    private static void sendSpiritDataToClient(ServerPlayerEntity player) {
        NbtCompound data = PLAYER_DATA_CACHE.get(player.getUuid());
        if (data != null) {
            // 发送数据包到客户端（需要实现网络通信逻辑）
            ClientDataManager.syncPlayerData(data);
        }
    }

    // 初始化灵异数据（只在第一次创建时调用）- 重命名以避免冲突
    public static void initSpiritData(PlayerEntity player) {
        if (!PLAYER_DATA_CACHE.containsKey(player.getUuid())) {
            PLAYER_DATA_CACHE.put(player.getUuid(), createDefaultSpiritData());
        }
    }
    // 查找指定类型物品的装备槽位
    public static int findEquippedItemSlot(PlayerEntity player, Class<? extends Item> itemClass) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            for (int i = 0; i < 6; i++) {
                String slotKey = "Slot" + i;
                if (ghostSlots.contains(slotKey)) {
                    NbtCompound slotData = ghostSlots.getCompound(slotKey);
                    if (slotData.getBoolean("occupied")) {
                        ItemStack item = ItemStack.fromNbt(slotData.getCompound("item"));
                        if (itemClass.isInstance(item.getItem())) {
                            return i;
                        }
                    }
                }
            }
        }
        return -1; // 未找到指定类型物品
    }

    // 查找已装备的鬼眼槽位(兼容旧接口)
    public static int findEquippedGhostEyeSlot(PlayerEntity player) {
        return findEquippedItemSlot(player, SilentGhostEyeItem.class);
    }

    // 获取玩家当前空的厉鬼槽位
    public static int getGhostSlot(PlayerEntity player) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            for (int i = 0; i < 6; i++) {
                String slotKey = "Slot" + i;
                if (ghostSlots.contains(slotKey)) {
                    NbtCompound slotData = ghostSlots.getCompound(slotKey);
                    if (!slotData.getBoolean("occupied")) {
                return i;
            }
                }
            }
        }
        return -1;
    }

    // 设置槽位数据
    public static void setGhostSlotData(PlayerEntity player, int slotIndex, ItemStack itemStack) {
    if (slotIndex < 0 || slotIndex >= 6) return;

    // 检查并移除旧物品属性
    ItemStack oldItem = getGhostSlotItem(player, slotIndex);
    if (oldItem.getItem() instanceof SilentGhostEyeItem) {
        subtractSpiritAttribute(player, SpiritAttributes.SPIRIT_RESISTANCE, 10);
        subtractSpiritAttribute(player, SpiritAttributes.SPIRIT_DAMAGE, 100);
        subtractSpiritAttribute(player, SpiritAttributes.REVIVAL_FACTOR, 2);
    }

    NbtCompound data = getCachedData(player);
    NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);

    NbtCompound slotData = new NbtCompound();
    slotData.putBoolean("occupied", true);
    slotData.put("item", itemStack.writeNbt(new NbtCompound()));
    slotData.putInt("level", 1);
    slotData.putInt("revivalDegree", 0);
    slotData.putInt("requiredRevivalDegree", 100);

    ghostSlots.put("Slot" + slotIndex, slotData);
    data.put(GHOST_SLOTS_KEY, ghostSlots);

    setSpiritAttributes(player, data);
    LOGGER.info("灵异装备槽位 {} 已设置为占用，物品: {}", slotIndex+1, itemStack.getItem().getName().getString());

    // 添加新物品属性
    if (itemStack.getItem() instanceof SilentGhostEyeItem) {
        addSpiritAttribute(player, SpiritAttributes.SPIRIT_RESISTANCE, 10);
        addSpiritAttribute(player, SpiritAttributes.SPIRIT_DAMAGE, 100);
        addSpiritAttribute(player, SpiritAttributes.REVIVAL_FACTOR, 2);
    }
}

    // 获取槽位中的物品
    public static ItemStack getGhostSlotItem(PlayerEntity player, int slotIndex) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            String slotKey = "Slot" + slotIndex;
            if (ghostSlots.contains(slotKey)) {
                NbtCompound slotData = ghostSlots.getCompound(slotKey);
                if (slotData.getBoolean("occupied") && slotData.contains("item")) {
                    return ItemStack.fromNbt(slotData.getCompound("item"));
                }
            }
        }
        return ItemStack.EMPTY;
    }

    // 检查槽位是否被占用
    public static boolean isGhostSlotOccupied(PlayerEntity player, int slotIndex) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            String slotKey = "Slot" + slotIndex;
            if (ghostSlots.contains(slotKey)) {
                NbtCompound slotData = ghostSlots.getCompound(slotKey);
                return slotData.getBoolean("occupied");
            }
        }
        return false;
    }

    // 获取槽位等级
    public static int getGhostSlotLevel(PlayerEntity player, int slotIndex) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            String slotKey = "Slot" + slotIndex;
            if (ghostSlots.contains(slotKey)) {
                NbtCompound slotData = ghostSlots.getCompound(slotKey);
                return slotData.getInt("level");
            }
        }
        return 1;
    }

    // 获取槽位厉鬼复苏程度
    public static int getGhostSlotRevivalDegree(PlayerEntity player, int slotIndex) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            String slotKey = "Slot" + slotIndex;
            if (ghostSlots.contains(slotKey)) {
                NbtCompound slotData = ghostSlots.getCompound(slotKey);
                return slotData.getInt("revivalDegree");
            }
        }
        return 0;
    }

    // 设置槽位复苏点数
    public static void setGhostSlotRevivalDegree(PlayerEntity player, int slotIndex, int revivalDegree) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            String slotKey = "Slot" + slotIndex;
            if (ghostSlots.contains(slotKey)) {
                NbtCompound slotData = ghostSlots.getCompound(slotKey);
                slotData.putInt("revivalDegree", revivalDegree);
                ghostSlots.put(slotKey, slotData);
                data.put(GHOST_SLOTS_KEY, ghostSlots);
                setSpiritAttributes(player, data);
            }
        }
    }
    // 清空槽位
    public static void clearGhostSlot(PlayerEntity player, int slotIndex) {
    NbtCompound data = getCachedData(player);
    if (data.contains(GHOST_SLOTS_KEY)) {
        NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
        String slotKey = "Slot" + slotIndex;
        if (ghostSlots.contains(slotKey)) {
            // 检查并移除鬼眼属性
            ItemStack oldItem = getGhostSlotItem(player, slotIndex);
            if (oldItem.getItem() instanceof SilentGhostEyeItem) {
                subtractSpiritAttribute(player, SpiritAttributes.SPIRIT_RESISTANCE, 10);
                subtractSpiritAttribute(player, SpiritAttributes.SPIRIT_DAMAGE, 100);
                subtractSpiritAttribute(player, SpiritAttributes.REVIVAL_FACTOR, 2);
            }
            
            NbtCompound slotData = new NbtCompound();
            slotData.putBoolean("occupied", false);
            slotData.put("item", ItemStack.EMPTY.writeNbt(new NbtCompound()));
            slotData.putInt("level", 1);
            slotData.putInt("revivalDegree", 0);
            slotData.putInt("requiredRevivalDegree", 100);
            ghostSlots.put(slotKey, slotData);
            data.put(GHOST_SLOTS_KEY, ghostSlots);
            setSpiritAttributes(player, data);
            LOGGER.info("灵异装备槽位 {} 已清空", slotIndex+1);
        }
    }
}

    // 获取所有槽位数据
    public static NbtCompound getGhostSlots(PlayerEntity player) {
        NbtCompound data = getCachedData(player);
        if (data.contains(GHOST_SLOTS_KEY)) {
            return data.getCompound(GHOST_SLOTS_KEY);
        }
        return new NbtCompound();
    }

    // 验证槽位数据
    public static void validateGhostSlots(PlayerEntity player) {
        NbtCompound data = getCachedData(player);
        LOGGER.info("=== 验证玩家 {} 的槽位数据 ===", player.getName().getString());

        if (data.contains(GHOST_SLOTS_KEY)) {
            NbtCompound ghostSlots = data.getCompound(GHOST_SLOTS_KEY);
            for (int i = 0; i < 6; i++) {
                String slotKey = "Slot" + i;
                if (ghostSlots.contains(slotKey)) {
                    NbtCompound slotData = ghostSlots.getCompound(slotKey);
                    boolean occupied = slotData.getBoolean("occupied");
                    LOGGER.info("灵异装备槽位 {}: occupied={}", i+1, occupied);
                } else {
                    LOGGER.info("槽位 {}: 无数据", i);
                }
            }
        } else {
            LOGGER.info("无GHOST_SLOTS_KEY数据");
        }
    }
}